package com.dg.cuckoo.admin.service.impl;

import com.dg.cuckoo.admin.dto.basicInformation.label.OneLabelDto;
import com.dg.cuckoo.admin.dto.basicInformation.permissionSettings.UnitTypeDto;
import com.dg.cuckoo.admin.repository.UnitTypeRepository;
import com.dg.cuckoo.admin.service.UnitTypeService;
import com.dg.cuckoo.common.utils.PageModel;
import com.dg.cuckoo.core.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UnitTypeServiceimpl implements UnitTypeService {

    @Autowired
    private UnitTypeRepository repository;

    @Override
    public void save(UnitTypeDto dto) {
        checkSave(dto);
        if(dto.getStatus()==null){
            dto.setStatus(1);
        }
        repository.save(dto);
    }

    @Override
    public void delect(String id) {
        if(id==null){
            throw new ServiceException("请选择单位类型");
        }
        repository.deleteById(id);
    }

    @Override
    public void disable(String id) {
        if(id==null){
            throw new ServiceException("请选择单位类型");
        }
        UnitTypeDto dto = repository.findById(id).get();
        dto.setStatus(0);
        repository.save(dto);
    }

    @Override
    public void start(String id) {
        if(id==null){
            throw new ServiceException("请选择单位类型");
        }
        UnitTypeDto dto = repository.findById(id).get();
        dto.setStatus(1);
        repository.save(dto);
    }

    @Override
    public UnitTypeDto openSelect(String id) {
        if(id==null){
            throw new ServiceException("请选择单位类型");
        }
        return repository.findById(id).get();
    }

    @Override
    public PageModel page(Integer page, Integer pageSize) {
        Integer one = page;
        page = (page - 1) * pageSize;
        int size = repository.findAll().size();
        List<UnitTypeDto> list = repository.page(page, pageSize);
        return new PageModel(one,pageSize,size,list);
    }

    @Override
    public void update(String id, UnitTypeDto dto) {
        if (id==null){
            throw new ServiceException("请选择行");
        }
        dto.setId(id);
        repository.save(dto);
    }

    public void checkSave(UnitTypeDto dto){
        if(dto.getTypeName()==null){
            throw new ServiceException("类型名称不能为空");
        }
        UnitTypeDto typeDto = repository.findByTypeName(dto.getTypeName());
        if(typeDto!=null){
            throw new ServiceException("类型名称已存在");
        }

    }
}
